package ar.com.jwa.services.impl;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import ar.com.jwa.domain.Game;
import ar.com.jwa.domain.State;
import ar.com.jwa.domain.User;
import ar.com.jwa.services.GameLocalService;

public class GameLocalServiceImpl implements GameLocalService {

	private static final Log log = LogFactory.getLog(GameLocalServiceImpl.class);
	private EntityManager em;
	
	@Transactional
	public void saveGame(Game game) {
		log.error("saving game");
		em.persist(game);
	}
	
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}


	
	/**
	 * Sacar esta funcion
	 */
	@Override
	@Transactional
	public boolean hasToConfirmSomething(User user) {
		Collection<Game> games = em.createQuery("select G FROM ar.com.jwa.domain.Game G where G.state ='" + State.TO_CONFIRM.ordinal() + "' or G.state = '"+ State.CONFIRMAED.ordinal() +"' order by G.id desc").getResultList();
		if (games.size() != 0) {
			Game game = games.iterator().next();
			if (game.hasPlayer(user)){
				return false;
			}
		}
		return true;
	}
	
	@Override
	@Transactional
	public Collection<Game> getGamesToConfirm() {
		Collection<Game> games = em.createQuery("select G FROM ar.com.jwa.domain.Game G where G.state ='" + State.TO_CONFIRM.ordinal() + "' or G.state = '"+ State.CONFIRMAED.ordinal() +"' order by G.id desc").getResultList();
		return games;
	}

	/**
	 * @return the em
	 */
	public EntityManager getEm() {
		return em;
	}
	
	/**
	 * @param em the em to set
	 */
	public void setEm(EntityManager em) {
		this.em = em;
	}

}
